<script setup>
import { ref, onMounted } from 'vue'
import { projectAreaListApi } from '@/service'
import AntdIcon from '@/components/AntdIcon/index.vue'
import AddCountry from './Addcountry.vue'
import { message, Modal } from 'ant-design-vue'
import { deleteProjectAreaApi } from '@/service'

const addCountryRef = ref()
const countryList = ref([])
const colums = [
  {
    key: 'id',
    title: '#',
    dataIndex: 'id',
  },
  {
    key: 'project_area_name',
    title: '国家/地区',
    dataIndex: 'project_area_name',
  },
  {
    key: 'create_time',
    title: '创建时间',
    dataIndex: 'create_time',
  },
  {
    key: 'action',
    title: '操作',
  },
]

const getCountryList = () => {
  projectAreaListApi().then((res) => {
    countryList.value = []
    const keys = Object.keys(res)
    keys.forEach((item) => {
      countryList.value.push({
        continent_id: item,
        continent_name:
          item === '1'
            ? '美洲'
            : item === '2'
              ? '欧洲'
              : item === '3'
                ? '亚洲'
                : item === '4'
                  ? '大洋洲'
                  : '非洲',
        country: res[item],
      })
    })
  })
}

const showModal = (type, info) => {
  if (type === 'add') {
    addCountryRef.value.open()
  } else {
    const { project_area_name, project_area_state, id: project_area_id } = info
    addCountryRef.value.open({
      project_area_name,
      project_area_state,
      project_area_id,
    })
  }
}
const delCountry = (project_area_id) => {
  Modal.confirm({
    title: '删除国家/地区',
    content: '确定删除该国家/地区吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      deleteProjectAreaApi({ project_area_id }).then(() => {
        message.success('删除成功')
        getCountryList()
      })
    },
  })
}

onMounted(() => {
  getCountryList()
})
</script>
<template>
  <div class="flex flex-col gap-5">
    <a-card>
      <a-button type="primary" @click="showModal('add')">添加国家/地区</a-button>
    </a-card>
    <a-card :title="item.continent_name" v-for="item in countryList" :key="item.continent_id">
      <a-table :columns="colums" :data-source="item.country" :pagination="false">
        <template #bodyCell="{ column, text, record }">
          <div v-if="column.key !== 'action'">
            {{ text }}
          </div>
          <div class="flex gap-3" v-else>
            <a-button type="primary" @click="showModal('edit', record)">
              <template #icon>
                <AntdIcon icon="EditOutlined" />
              </template>
            </a-button>
            <a-button type="primary" danger @click="delCountry(record.id)">
              <template #icon>
                <AntdIcon icon="DeleteOutlined" />
              </template>
            </a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    <AddCountry ref="addCountryRef" @addCountry="getCountryList" />
  </div>
</template>
